from rest_framework.viewsets import GenericViewSet
from rest_framework.decorators import action
from django.core.cache import cache
# 线上环境不能使用多线程
# from threading import Thread
# 考虑使用celery异步执行任务
from .models import User
from .serializers import MulLoginSerializer, SmsLoginSerializer, RegisterSerializer
from celery.result import AsyncResult
from utils.common_response import APIResponse
from .tasks import sec_kill, app
# 日志记录
# from utils.loggers import log_uru
# 腾讯云发短信
from libs.tx_sms import get_code, send_sms


class UserMobileView(GenericViewSet):
    '''
    关于手机号的视图类
    '''

    @action(['get'], detail=False)
    def exist(self, request, *args, **kwargs):
        # 从携带的参数获取手机号 ?mobile=xxx
        mobile = request.query_params.get('mobile')
        is_exist = True if User.objects.filter(mobile=mobile) else False
        return APIResponse(result=is_exist)

    @action(['get'], detail=False)
    def sms(self, request, *args, **kwargs):
        # 获取电话
        mobile = request.query_params.get('mobile')
        # 生成验证码
        code = get_code()
        # 将验证码存放到缓存中供后续校验
        cache.set(f'cache_code_{mobile}', code, 600)
        # 提交celery异步任务
        send_sms.delay(mobile, code)
        # t = Thread(target=send_sms, args=(mobile, code))
        # t.start()
        return APIResponse(msg='短信已发送')


class LoginView(GenericViewSet):

    def get_serializer_class(self):
        if self.action == 'mul_login':
            return MulLoginSerializer
        else:
            return SmsLoginSerializer

    @action(methods=['post'], detail=False)
    def mul_login(self, request, *args, **kwargs):
        return self._common_login(request, *args, **kwargs)

    @action(methods=['post'], detail=False)
    def sms_login(self, request, *args, **kwargs):
        return self._common_login(request, *args, **kwargs)

    def _common_login(self, request, *args, **kwargs):
        '''
        封装一个公用的登录函数
        '''
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        token = serializer.context.get('token')
        # 使用序列化返回用户名和头像
        data = serializer.data
        return APIResponse(token=token, username=data.get('username'), icon=data.get('icon'))


class RegisterView(GenericViewSet):
    serializer_class = RegisterSerializer

    def create(self, request, *args, **kwargs):
        # 逻辑写在序列化类中
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return APIResponse(msg='注册成功')


class SecKillView(GenericViewSet):
    @action(methods=['POST'], detail=False)
    def sec_kill(self, request, *args, **kwargs):
        course_id = request.data.get('course_id')
        task_id = sec_kill.delay(course_id)
        return APIResponse(msg='您正在排队', task_id=str(task_id))

    @action(methods=['GET'], detail=False)
    def get_result(self, request, *args, **kwargs):
        task_id = request.query_params.get('task_id')
        a = AsyncResult(id=task_id, app=app)
        if a.successful():
            result = a.get()  # True 和 False
            if result:
                return APIResponse(success='1', msg='秒杀成功')
            else:
                return APIResponse(success='0', msg='秒杀失败')
        elif a.status == 'PENDING':
            return APIResponse(success='2', msg='任务等待中被执行')
        else:
            return APIResponse(success='3', msg='秒杀任务正在执行')
